import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

// 通过扫描方式加载路由
function loadRoutes() {
    let routes = [];
    const files = require.context('./modules', false, /.js$/);
    files.keys().forEach(key => {
        if (key.startsWith('./index')) {
            return false;
        }
        routes = [...routes, ...(files(key).default || files(key))];
    });

    return routes;
}

const routes = [
    {
        path: '/',
        redirect: {
            name: 'home'
        },
        component: () => import('@/views/home/index.vue'),
        meta: {
            title: '首页',
            keepAlive: true
        }
    },
    {
        path: '/home',
        name: 'home',
        meta: {
            title: '首页',
            keepAlive: true
        },
        component: () => import('@/views/home/index.vue')
    },
    ...loadRoutes()
];

const router = new VueRouter({
    mode: 'hash',
    routes
});

router.beforeEach((to, from, next) => {
    const title = to.meta && to.meta.title;
    if (title) {
        document.title = title;
    }
    next();
});

export default router;
